package com.me.Persistence;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by wangyg on 2016/11/7.
 */
public class MessagePersistence {
	public void doPersist() throws JMSException {
		//	3.3 消息的持久订阅
		// 连接到ActiveMQ服务器
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
		Connection connection = factory.createConnection();
		String ip = "";
		try

		{
			// 获取本机IP
			InetAddress addr = InetAddress.getLocalHost();
			ip = addr.getHostAddress().toString();
		} catch (UnknownHostException ex) {
			ex.printStackTrace();
			ip = "";
			if (!"".equals(ip)) {
				System.out.println("CLIENT: " + ip);
				// 设置订阅客户端ID
				connection.setClientID(ip);
				connection.start();
				Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
				// 创建主题
				Topic topic = session.createTopic("myTopic.messages");
				// 创建订阅
				MessageConsumer consumer = session.createDurableSubscriber(topic, "test");
				consumer.setMessageListener(new MessageListener() {
					// 订阅接收方法
					public void onMessage(Message message) {
						TextMessage tm = (TextMessage) message;
						try {
							System.out.println("Received message: " + tm.getText());
						} catch (JMSException e) {
							e.printStackTrace();
						}
					}
				});
			}
		}
	}
}
